/**
 * 组件级tooltip（整个组件作为别的组件的tooltip）交互
 */
import { mapState, mapMutations } from 'vuex';

export default {
  data() {
    return {
      asTooltipFilter: {

        // 根据当前组件 config.propertyPannelName 提取key
        'single_header_page_table': 'pageTableFilter',
      },
      asTooltipWatcher: null,
    };
  },
  computed: {
    ...mapState({
      asTooltips: state => state.VisualComponentsModule.asTooltips,
      asTooltipUsers: state => state.VisualComponentsModule.asTooltipUsers,
    }),
  },

  watch: {},
  beforeDestroy() {
    this.destoryAsTooltip();
    this.clearAsTooltip(this.widgetInstanceId);
  },

  methods: {
    ...mapMutations(['setAsTooltip', 'clearAsTooltip', 'setAsTooltipUser', 'clearAsTooltipUser']),

    // 当前组件作为其他组件的tooltip
    initAsTooltip() {
      const { tooltip } = this.config.config.property;
      const wid = this.widgetInstanceId;
      if (!tooltip) {
        return;
      }
      const key = (tooltip.asTooltip && tooltip.asTooltipKey) || '';
      this.clearAsTooltip(wid);
      const tableData = (this.config.config.data && this.config.config.data.tableData) || [];
      this.setAsTooltip({
        wid,
        pageId: this.pageId,
        asTooltipKey: key,
        tableData,
      });

      if (!window.asTooltipDoms) {
        window.asTooltipDoms = {};
      }

      // 点击“应用”时保证dom显示在原始位置
      Object.entries(window.asTooltipDoms).map(([i]) => {
        const n = window.asTooltipDoms[i];
        if (n.wid === wid) {
          n.parent.appendChild(n.widget);

          // 组件key修改过，清除原来的
          if (i !== key) {
            delete window.asTooltipDoms[i];
          }
        }
      });

      // 将组件索引存入window变量
      if (key) {
        const widget = document.getElementById(`widgetBox_${wid}`);
        if (widget) {
          window.asTooltipDoms[key] = {
            wid,
            widget,
            parent: widget.parentElement,
          };
        }
      } else {
        const { asTooltipKey } = tooltip;
        if (asTooltipKey) {
          delete window.asTooltipDoms[asTooltipKey];
        }
      }

      this.watchAsTooltipUsers();
    },

    // 组件使用别的组件tooltip时
    initAsTooltipUser() {
      const { tooltip } = this.config.config.property;
      const wid = this.widgetInstanceId;
      this.clearAsTooltipUser(wid); // 清空原有配置
      if (tooltip && !tooltip.asTooltip && tooltip.asTooltipUsers) {
        tooltip.asTooltipUsers.forEach(n => {
          this.setAsTooltipUser({
            wid,
            isHovering: false,
            vars: {},
            ...n,
          });
        });
      }
    },

    // 销毁前删除window内存引用，防止内存溢出
    destoryAsTooltip() {
      const wid = this.widgetInstanceId;
      Object.entries(window.asTooltipDoms || {}).map(([i]) => {
        const n = window.asTooltipDoms[i];
        if (n.wid === wid) {
          delete window.asTooltipDoms[i];
        }
      });
    },

    // 公共过滤器
    commonFilter(apiRes, vars) {
      const _apiRes = apiRes.filter(n => {
        let flag = true;
        for (const i in vars) {
          if (n[i] !== vars[i]) {
            flag = false;
            break;
          }
        }
        return flag;
      });
      return _apiRes;
    },

    // 表格过滤器
    pageTableFilter(apiRes, vars) {
      if (!apiRes.data) {
        return false;
      }
      apiRes.data = apiRes.data.filter(n => {
        let flag = true;
        for (const i in vars) {
          if (n[i] !== vars[i]) {
            flag = false;
            break;
          }
        }
        return flag;
      });
      apiRes.total = apiRes.data.length;
      return apiRes;
    },

    getFilterResult() {
      if (!this.apiResult) {
        return false;
      }

      const wid = this.widgetInstanceId;
      const tipWidget = this.asTooltips.find(n => n.wid === wid);
      if (!tipWidget) {
        return false;
      }

      const { asTooltipKey } = tipWidget;
      const users = this.asTooltipUsers;
      const user = users.find(n => n.isHovering && n.asTooltipKey === asTooltipKey);
      if (!user) {
        return false;
      }

      let apiRes = JSON.parse(JSON.stringify(this.apiResult));
      const { propertyPannelName } = this.config;
      const filterKey = propertyPannelName.replace(`config_${process.env.xvueNameSpace_}`, '');
      const method = this.asTooltipFilter[filterKey];
      if (user.correlation === 'correlate') {
        if (this[method]) {
          apiRes = this[method](apiRes, user.vars);
        } else {
          apiRes = this.commonFilter(apiRes, user.vars);
        }
      }
      return apiRes;
    },

    watchAsTooltipUsers() {
      if (this.asTooltipWatcher) {
        this.asTooltipWatcher();
      }

      const { tooltip } = this.config.config.property;
      const key = (tooltip && tooltip.asTooltip && tooltip.asTooltipKey) || '';
      if (key) {
        this.asTooltipWatcher = this.$watch(
          () => {
            const user = this.asTooltipUsers.find(n => n.asTooltipKey === key && n.isHovering);
            return user;
          },
          newVal => {
            if (newVal) {
              const filterRes = this.getFilterResult();
              if (filterRes) {
                this.handleAsTooltip(filterRes);
              }
            }
          },
          { deep: true, immediate: true },
        );
      }
    },
  },
};
